package com.hunan.api.catv.service.biz.mall;

import com.alibaba.druid.support.json.JSONUtils;
import com.google.gson.JsonObject;
import com.hunan.api.catv.common.CacheKey;
import com.hunan.api.catv.common.CacheName;
import com.hunan.api.catv.common.Constants;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.enums.LoginType;
import com.hunan.api.catv.entity.vo.MemberVo;
import com.hunan.api.catv.entity.vo.mall.youzan.YouzanLoginReqVo;
import com.hunan.api.catv.entity.vo.mall.youzan.YouzanLoginResVo;
import com.hunan.api.catv.entity.vo.mall.youzan.YouzanLogoutReqVo;
import com.hunan.api.catv.entity.vo.mall.youzan.YouzanLogoutResVo;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.apple.AppleBiz;
import com.hunan.api.catv.service.biz.cache.CacheBiz;
import com.hunan.api.catv.service.biz.member.MemberBiz;
import com.hunan.api.catv.service.biz.member.open.MemberOpenBiz;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;

@Service
@CacheConfig(cacheNames = CacheName.youzanMall)
public class YouzanMallBiz extends ResultService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private CacheBiz cacheBiz;

    @Autowired
    private RestTemplate baseRestTemplate;

    @Value("${mall.youzan.login}")
    private String loginUrl;

    @Value("${mall.youzan.login}")
    private String logoutUrl;

    @Value("${mall.youzan.clientId}")
    private String clientId;

    @Autowired
    private MemberOpenBiz memberOpenBiz;

    @Autowired
    private AppleBiz appleBiz;

    @Autowired
    private MemberBiz memberBiz;

    /**
     * 有赞商城登陆
     *
     * @param memberId
     * @return
     */
    public ServiceResult login(Integer memberId) {
        if (null != memberId) {
            String appleUserInfoKey = MessageFormat.format(CacheKey.member_appleUserInfo, memberId);
            MemberVo memberVo = new MemberVo();
            if (ObjectUtils.isEmpty(redisUtils.get(appleUserInfoKey))) {
                String memberIdStr = String.valueOf(memberId);
                ServiceResult verifyResult = appleBiz.verify(memberIdStr);
                if (verifyResult.status) {
                    ServiceResult userResult = appleBiz.getUserInfo(memberIdStr);
                    if (userResult.getStatus()) {
                        JsonObject info = GsonUtils.fromJson(userResult.getData().toString(), JsonObject.class);
                        String sub = info.get("sub").getAsString();
                        memberVo = memberBiz.infoById(LoginType.apple.getCode(), sub);
                    }
                }
            }

            String youzanOpenId = memberOpenBiz.getMemberThirdOpenId(Integer.valueOf(memberId), Constants.OPEN_ID_TYPE_FOR_YOUZAN);
            if (null == youzanOpenId) {
                return buildFail(false, ConstantsMsg.youzan_get_open_fail);
            }
            YouzanLoginReqVo youzanLoginReqVo = new YouzanLoginReqVo();
            youzanLoginReqVo.setClient_id(clientId);
            youzanLoginReqVo.setOpen_user_id(youzanOpenId);
            youzanLoginReqVo.setAvatar(memberVo.getAvatarUrl());
            youzanLoginReqVo.setExtra("");
            youzanLoginReqVo.setNick_name(memberVo.getNickName());
            //YouzanLoginReqVo req = new YouzanLoginReqVo();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_UTF8_VALUE);
            MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
            postParameters.add("client_id", clientId);
            postParameters.add("open_user_id", youzanOpenId);
            postParameters.add("avatar", memberVo.getAvatarUrl());
            postParameters.add("extra", "");
            postParameters.add("nick_name", memberVo.getNickName());
            HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(postParameters, headers);
            YouzanLoginResVo res = null;
            try {
                res = baseRestTemplate.postForEntity(loginUrl, formEntity, YouzanLoginResVo.class).getBody();
            } catch (Exception e) {
                log.error("调用有赞登录接口出错：", e);
                return buildFail(false, ConstantsMsg.youzan_auth_remote_fail);
            }
            if (null != res) {
                //JsonObject youzanLoginJson = new JsonObject();
                if (res.getCode() == 0) {
                    return buildOK(res, "有赞商城登录成功");
                } else {
                    return buildFail(res, "有赞远程登录接口返回登录失败");
                }

            }
        }
        return buildFail(false, ConstantsMsg.youzan_auth_fail);
    }

    /**
     * 有赞商城登出
     *
     * @param memberId
     * @return
     */
    public ServiceResult logout(Integer memberId) {
        if (null != memberId) {
            YouzanLogoutResVo res = null;
            HttpHeaders headers = new HttpHeaders();
            YouzanLogoutReqVo req = new YouzanLogoutReqVo();
            String youzanOpenId = memberOpenBiz.getMemberThirdOpenId(memberId, Constants.OPEN_ID_TYPE_FOR_YOUZAN);
            if (null == youzanOpenId) {
                return buildFail(false, ConstantsMsg.youzan_get_open_fail);
            }
            req.setOpenUserId(youzanOpenId);
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_UTF8_VALUE);
            HttpEntity<String> formEntity = new HttpEntity<>(JSONUtils.toJSONString(req), headers);
            try {
                res = baseRestTemplate.postForEntity(logoutUrl, formEntity, YouzanLogoutResVo.class).getBody();

            } catch (Exception e) {
                log.error("调用有赞登出接口出错：", e);
                return buildFail(false, ConstantsMsg.youzan_auth_remote_logout_fail);
            }
            if (null != res) {
                return buildOK(res, "有赞登出成功");
            }
        }
        return buildFail(false, ConstantsMsg.youzan_logout_fail);
    }

}
